//
//  tool.m
//  yifa
//
//  Created by 刘亨平 on 15/7/11.
//  Copyright (c) 2015年 liuhengping. All rights reserved.
//

#import "tool.h"

@implementation tool

+ (UIColor *)randomColor
{

    CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:0.7];

}

#pragma mark - 输入16进制的设置转化成uicolor
+ (UIColor *)getColor:(NSString*)hexColor

{
    unsigned int red,green,blue;
    
    NSRange range;
    
    range.length = 2;
    
    range.location = 0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];
    
    range.location = 2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green / 255.0f) blue:(float)(blue / 255.0f)alpha:1.0f];
    
}

#pragma mark - 根据色织 生成图片填充
+(UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark - 数字的校验
+ (BOOL)validateNumber:(NSString*)number
{
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0)
        {
            res = NO;
            break;
        }
        i++;
    }
    
    return res;
}

#pragma mark - json 转化 成 字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


+ (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize
{
    //先调整分辨率
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = newSize.height / 1024;
    CGFloat tempWidth = newSize.width / 1024;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
    NSUInteger sizeOrigin = [imageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    if (sizeOriginKB > maxSize) {
        NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50);
        return finallImageData;
    }
    
    return imageData;
}


#pragma mark - json 转化 成 数组
+ (NSArray *)arrayWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark - 去掉json的斜杠
+(NSMutableString *)replaceJsonxiegang:(id)_json
{

NSMutableString *responseString = [NSMutableString stringWithString:[NSString stringWithFormat:@"%@",_json]];
NSString *character = nil;
for (int i = 0; i < responseString.length; i ++) {
    character = [responseString substringWithRange:NSMakeRange(i, 1)];
    if ([character isEqualToString:@"\\"])
    {
        [responseString deleteCharactersInRange:NSMakeRange(i, 1)];
    }
}
    
    return responseString;

}


#pragma mark - 生成json格式的文本
+(NSString *)returnjson:(id)params
{
    NSData* jsonData =[NSJSONSerialization dataWithJSONObject:params
                                                      options:NSJSONWritingPrettyPrinted error:nil];
    NSString* post_paramsJSON =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return post_paramsJSON;
}

#pragma mark - 设定文本框起始位置
+(void)addleftview_for_textfield:(UITextField *)textfield
{

textfield.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, 0)];
textfield.leftViewMode = UITextFieldViewModeAlways;

}



#pragma mark - 根据需求返回日期信息
+(NSString *)returnDate:(NSString *)sType diff:(NSInteger)_diff formatter:(NSString *)_formatter
{
    NSArray *tArray = [NSArray arrayWithObjects:@"this",@"diff",nil];
    NSInteger index = [tArray  indexOfObject:sType];
    
    NSDate *returndate = [NSDate date];
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    date = [date  dateByAddingTimeInterval: interval];
    
    switch (index) {
        case 0:
            returndate=date;
            break;
        case 1:
            returndate = [date dateByAddingTimeInterval: _diff*24*60*60];
            break;
    }
    
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    if(![_formatter isEqualToString:@""])
    {
        [dateFormatter setDateFormat:_formatter];
    }
    
    return [dateFormatter stringFromDate:returndate] ;
}


 
+(UIImage *)imageWithBgColor:(UIColor *)color {
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}


+(void)httploading:(UIView *)atview title:(NSString *)title
{
    //加入loading
    
//   MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:atview animated:YES];
//    hud.labelText=title;
//    hud.dimBackground = NO;
//    hud.removeFromSuperViewOnHide = YES;
//    [hud show:YES];
}

+(void)addMUtablearray:(NSMutableArray *)mutablearray arrtemp:(NSArray *)arrtemp
{
     for(int i=0;i<arrtemp.count;i++)
    {
        [mutablearray addObject:arrtemp[i]];
    }
}

#pragma mark - 将13位的时间戳转化为时间格式数据
+(NSString *)returndate_add13timeStamp:(NSString *)timeStampString
{
    NSTimeInterval _interval=[timeStampString doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *strDate=[objDateformat stringFromDate: date];
    
    return strDate;
}

+ (NSDate *)dateFromString1:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    return destDate;
    
}


+(NSString *)returndate1:(NSString *)_add format:(NSString *)_format
{
    NSDate* now =[self dateFromString1:_add];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    fmt.dateFormat = _format;
    NSString* dateString = [fmt stringFromDate:now];
    return dateString;
}


+(void) setattrtext:(UILabel *)lab text:(NSString *)text start:(NSInteger)start
{
    NSMutableAttributedString *attributedStr_price = [[NSMutableAttributedString alloc] initWithString: text];
    [attributedStr_price addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(0, start)];
    [attributedStr_price addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(start,text.length-(start+1))];
    [attributedStr_price addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(text.length-1,1)];
    
    lab.attributedText=attributedStr_price;
}


//+(NSString *) returnImageURl:(NSString *)imageid
//{
//    NSString *strurl=[NSString stringWithFormat:getimage,imageid];
//    strurl=[IDE stringByAppendingString:strurl];
//    
//    return strurl;
//}
//
//
//+(NSString *) returnThumbImageURl:(NSString *)imageid
//{
//    NSString *strurl=[NSString stringWithFormat:getthumbimage,imageid];
//    strurl=[IDE stringByAppendingString:strurl];
//    
//    return strurl;
//}




@end
